package com.ktjiaoyu.crm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RoleService;
import com.ktjiaoyu.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 查询用户列表
     * @param pageIndex 当前页
     * @param usrName   用户名
     * @param roleId    角色ID
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/list")
    public String findUsers(@RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex,String usrName, Long roleId, Model model){
        //实例化Page对象
        Page<User> page = new Page<>(pageIndex,5);
        //第二种：返回list，再调用setRecoreds()返回page对象
        page = userService.selectUserPages(page,usrName,roleId);

        //查询条件回写
        model.addAttribute("roleId",roleId);
        model.addAttribute("usrName",usrName);
        //将数据返回到list页面
        model.addAttribute("userPager",page);

        return "user/list";
    }

    /**
     * 去到新增用户页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/add")
    public String add(Model model){
        List<Role> roleList = roleService.list();
        model.addAttribute("roles",roleList);
        return "user/add";
    }

    /**
     * 新增用户信息
     * @param user
     * @return
     */
    @RequestMapping(value = "/user/save")
    public String save(User user){
        if(userService.saveOrUpdate(user)) return "redirect:/user/list";

        return "redirect:/user/add";
    }

    /**
     * 去到修改用户页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/user/edit")
    public String update(Long usrId,Model model){
        //根据ID查询用户信息
        User user = userService.getById(usrId);
        //查询所有角色列表
        List<Role> roleList = roleService.list();
        model.addAttribute("user",user);
        model.addAttribute("roles",roleList);
        return "user/edit";
    }

    /**
     * 根据用户ID删除用户信息
     * @param usrId
     * @return
     */
    @GetMapping(value = "/user/del/{usrId}")
    @ResponseBody
    public Object delete(@PathVariable Long usrId){
        Map map = new HashMap();
        //调用删除方法
        int result = userService.deleteUserById(usrId);
        if(result>0){
            map.put("delResult",true);
        }else{
            map.put("delResult",false);
        }
        return map;
    }


}
